package com.simple.core.util;

import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@UtilityClass
public class HttpContext {

    public HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public String getDomain() {
        HttpServletRequest request = getHttpServletRequest();
        if (Objects.isNull(request)) return "";
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public String getOrigin() {
        HttpServletRequest request = getHttpServletRequest();
        if (Objects.isNull(request)) return "";
        return request.getHeader("Origin");
    }
}
